#include "qdrivelistdialog.h"

#include "../../lib/corelib/qcommondelegate.h"
#include "../../lib/shared/qproject.h"
#include "../../lib/shared/qdriveplugininterface.h"

#include <QVBoxLayout>
#include <QHeaderView>

QDriveListDialog::QDriveListDialog(QWidget *parent):
    QDialog(parent),
    m_treeView(new QCommonTreeWidget)
{
    this->setFixedSize(300,400);


    QVBoxLayout *l=new QVBoxLayout;
    l->setMargin(0);
    l->setSpacing(0);

    l->addWidget(m_treeView);
    this->setLayout(l);

    QMap<QString,tagDrivePluginInfo> plugins=QProject::project()->drivePlugins();

    QMapIterator<QString,tagDrivePluginInfo> it(plugins);


    while(it.hasNext())
    {
        it.next();
        if(it.value().m_drivePlugin->keys().size()==0)
        {
            continue;
        }
        QStringList list=it.key().split("/");
        QString ss;
        foreach(QString str,list)
        {
            QTreeWidgetItem *p=m_items.value(ss,NULL);
            QTreeWidgetItem *pp=m_items.value(ss+"/"+str,NULL);
            QTreeWidgetItem *temp;
            if(pp==NULL)
            {
                if(p==NULL)
                {
                    temp=new QTreeWidgetItem(m_treeView);
                }
                else
                {
                    temp=new QTreeWidgetItem(p);
                }
                temp->setText(0,str);
                temp->setToolTip(0,str);
                m_items.insert(ss+"/"+str,temp);
                ss+=("/"+str);
            }
        }
        QTreeWidgetItem *p=m_items.value("/"+it.key(),NULL);
        if(p!=NULL)
        {
            QStringList keys=it.value().m_drivePlugin->keys();
            foreach(QString drive,keys)
            {
                QTreeWidgetItem *temp=new QTreeWidgetItem(p);
                temp->setText(0,drive);
                temp->setToolTip(0,drive);
            }
        }

    }
    m_treeView->expandAll();

    connect(m_treeView,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(select(QTreeWidgetItem*,int)));
}

void QDriveListDialog::select(QTreeWidgetItem *item, int index)
{
    m_select="";
    QList<QTreeWidgetItem*> items=m_items.values();

    if(items.indexOf(item)>=0)
    {
        return;
    }

    m_select=":"+item->text(0);
    QTreeWidgetItem *parent=item->parent();

    while(1)
    {
        if(items.indexOf(parent)<0)
        {
            break;
        }
        m_select="/"+parent->text(0)+m_select;
        parent=parent->parent();
    }
    if(m_select.startsWith("/"))
    {
        m_select.remove(0,1);
    }
    close();
}

QString QDriveListDialog::getSelect()
{
    return m_select;
}
